<template>
  <avue-crud :option="option"
             :table-loading="loading"
             :data="data"
             v-model:page="page"
             v-model="form"
             ref="crud"
             @row-save="rowSave"
             @search-change="searchChange"
             @search-reset="searchReset"
             @selection-change="selectionChange"
             @current-change="currentChange"
             @size-change="sizeChange"
             @on-load="onLoad">
    <template #groupId="{ row }">
      <el-tag size="large" style="cursor: pointer" @click="viewDetail(row)">{{ row.groupName }}</el-tag>
    </template>
    <template #deviceName="{ row }">
      <el-tag size="large" style="cursor:pointer" @click="viewDetail(row)">{{ row.deviceName }}</el-tag>
    </template>
    <template #deviceSecret="{ row }">
      <el-tag size="large" style="cursor:pointer" @click="viewDetail(row)">{{ row.deviceSecret }}</el-tag>
    </template>
    <template #deviceStatus="{ row }">
      <el-tag v-if="row.deviceStatus===1" type="success" style="cursor: pointer">
        <el-icon>
          <SuccessFilled />
        </el-icon>
        {{ row.deviceStatusName }}
      </el-tag>
      <el-tag v-else-if="row.deviceStatus===2" type="danger" style="cursor: pointer">
        <el-icon>
          <WarningFilled />
        </el-icon>
        {{ row.deviceStatusName }}
      </el-tag>
      <el-tag v-else type="info" style="cursor: pointer">
        <el-icon>
          <CircleCloseFilled />
        </el-icon>
        {{ row.deviceStatusName }}
      </el-tag>
    </template>
    <template #menu-left>
      <el-button type="danger"
                 icon="el-icon-circle-close"
                 plain
                 @click="unbindGroups">解绑设备
      </el-button>
    </template>
    <template #menu="scope">
      <el-button text
                 type="primary"
                 icon="el-icon-view"
                 @click.stop="viewDetail(scope.row)">
        查看
      </el-button>
      <el-button text
                 type="primary"
                 icon="el-icon-circle-close"
                 @click.stop="unbindGroup(scope.row)">
        解绑
      </el-button>
    </template>
  </avue-crud>
</template>

<script>
import { getPage, getTable, getDetails } from '@/api/iot/device';
import { addGroupDevice, unbindGroupDevice } from '@/api/iot/group';


export default {
  name: 'groupDevice',
  props: {
    groupId: String
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 172,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        selection: true,
        menu: true,
        addBtnText: '添加设备',
        emptyText: '当前分组并未分配任何设备',
        dialogWidth: 500,
        labelWidth: 120,
        searchLabelWidth: 100,
        column: [
          {
            label: '设备名称',
            prop: 'deviceName',
            type: 'input',
            slot: true,
            display: false,
            span: 24
          },
          {
            label: '设备密钥',
            prop: 'deviceSecret',
            type: 'input',
            slot: true,
            display: false,
            span: 24
          },
          {
            label: '设备所属产品',
            prop: 'productName',
            type: 'input',
            display: false,
            span: 24
          },
          {
            label: '设备状态',
            prop: 'deviceStatus',
            type: 'input',
            slot: true,
            display: false,
            width: 120,
            span: 24
          },
          {
            label: '最后上线时间',
            prop: 'lastOnlineTime',
            type: 'input',
            display: false,
            width: 180,
            span: 24
          },
          {
            label: '设备集合',
            labelTip: '可选择设备集合绑定至此分组',
            prop: 'deviceId',
            type: 'table',
            multiple: true,
            editDisabled: true,
            hide: true,
            children: {
              border: true,
              column: [{
                label: '设备ID',
                prop: 'id',
                hide: true
              }, {
                label: '产品编号',
                prop: 'productKey',
                search: true,
                width: 200
              }, {
                label: '设备名称',
                prop: 'deviceName',
                search: true,
                width: 250
              }, {
                label: '设备密钥',
                prop: 'deviceSecret',
                search: true
              }, {
                label: '唯一编号',
                prop: 'uniqueNo',
                search: true
              }, {
                label: '设备状态',
                prop: 'deviceStatusName',
                width: 120
              }, {
                label: '激活时间',
                prop: 'activeTime',
                width: 180
              }]
            },
            formatter(row) {
              if (Array.isArray(row)) {
                return row.map(ele => ele.deviceName).join(',');
              } else {
                return row.deviceName;
              }
            },
            onLoad: ({ page, value, data }, callback) => {
              let param = {};
              let currentPage = 1;
              let pageSize = 10;

              if (value) {
                getDetails(value).then(res => {
                  callback(res.data.data);
                });
                return;
              }
              if (data) {
                param = data;
              }
              if (page) {
                currentPage = page.currentPage;
                pageSize = page.pageSize;
              }
              getTable(currentPage, pageSize, Object.assign(param, { groupId: this.groupId })).then(res => {
                const data = res.data.data;
                //分页查询信息
                callback({
                  total: data.total,
                  data: data.records
                });
              });
            },
            props: {
              label: 'deviceName',
              value: 'id'
            },
            span: 24,
            rules: [{
              required: true,
              message: '请选择设备集合',
              trigger: 'change'
            }]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
    },
    rowSave(row, done, loading) {
      addGroupDevice(row.deviceId, this.groupId).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
        this.onLoad(this.page);
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    viewDetail(row) {
     window.open(`/iot/device/detail/${row.productKey}/${row.deviceName}`);
    },
    unbindGroup(row) {
      this.$confirm(`是否解绑所选设备[${row.deviceName}]的分组?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        unbindGroupDevice(row.id, this.groupId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      });
    },
    unbindGroups() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条设备数据");
        return;
      }
      this.$confirm("确定将选择设备数据解绑?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        unbindGroupDevice(this.ids, this.groupId).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getPage(page.currentPage, page.pageSize, this.groupId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
